﻿using Roton.ZZT;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Roton.File
{
    /// <summary>
    /// A Disk class that works with the user's own filesystem.
    /// </summary>
    public class Disk : IDisk
    {
        private string path;

        public Disk(string path)
        {
            this.path = path;
        }

        public void ChangeDirectory(ByteString relativeDirectory)
        {
            string targetDirectory = Path.Combine(path, relativeDirectory);
            if (Directory.Exists(targetDirectory))
                path = targetDirectory;
        }

        public ByteString[] GetDirectoryList()
        {
            List<ByteString> result = new List<ByteString>();
            List<string> directories = new List<string>();
            directories.AddRange(Directory.GetDirectories(path));
            directories.Sort();

            // check to see if the path is the root. if not, add ".."
            DirectoryInfo di = new DirectoryInfo(path);
            if (di.Parent != null)
                result.Add(new ByteString(".."));

            int count = directories.Count;
            for (int i = 0; i < count; i++)
                result.Add(Path.GetDirectoryName(directories[i]));
            return result.ToArray();
        }

        public ByteString[] GetFileList(ByteString filter)
        {
            string[] files = Directory.GetFiles(path);
            ByteString[] result = new ByteString[files.Length];
            int count = files.Length;

            for (int i = 0; i < count; i++)
                result[i] = Path.GetDirectoryName(files[i]);
            return result;
        }

        public Stream LoadFile(ByteString fileName)
        {
            using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                return new MemoryStream(buffer);
            }
        }

        public void SaveFile(ByteString fileName, Stream data, int length)
        {
            using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Create, FileAccess.Write, FileShare.Read))
            {
                byte[] buffer = new byte[length];
                data.Read(buffer, 0, length);
                fs.Write(buffer, 0, length);
            }
        }
    }
}
